import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        // 全局状态
        isLoading: false, currentUser: null,

        // 练习相关状态
        practiceSettings: {
            speedJudge: {
                questionCount: 5
            }, speedCalc: {
                questionCount: 10, operations: ['add', 'subtract'], valueTypes: ['integer']
            }
        },

        // 练习数据
        currentPractice: null, practiceResults: null
    },

    mutations: {
        SET_LOADING(state, loading) {
            state.isLoading = loading;
        },

        SET_CURRENT_USER(state, user) {
            state.currentUser = user;
        },

        SET_PRACTICE_SETTINGS(state, {type, settings}) {
            state.practiceSettings[type] = {...state.practiceSettings[type], ...settings};
        },

        SET_CURRENT_PRACTICE(state, practice) {
            state.currentPractice = practice;
        },

        SET_PRACTICE_RESULTS(state, results) {
            state.practiceResults = results;
        },

        CLEAR_PRACTICE_DATA(state) {
            state.currentPractice = null;
            state.practiceResults = null;
        }
    },

    actions: {
        // 设置加载状态
        setLoading({commit}, loading) {
            commit('SET_LOADING', loading);
        },

        // 更新练习设置
        updatePracticeSettings({commit}, {type, settings}) {
            commit('SET_PRACTICE_SETTINGS', {type, settings});
        },

        // 开始练习
        startPractice({commit}, practice) {
            commit('SET_CURRENT_PRACTICE', practice);
        },

        // 完成练习
        completePractice({commit}, results) {
            commit('SET_PRACTICE_RESULTS', results);
        },

        // 清除练习数据
        clearPracticeData({commit}) {
            commit('CLEAR_PRACTICE_DATA');
        }
    },

    getters: {
        // 是否正在加载
        isLoading: state => state.isLoading,

        // 获取练习设置
        getPracticeSettings: state => type => state.practiceSettings[type],

        // 获取当前练习
        getCurrentPractice: state => state.currentPractice,

        // 获取练习结果
        getPracticeResults: state => state.practiceResults,

        // 检查是否有进行中的练习
        hasActivePractice: state => !!state.currentPractice,

        // 检查是否有练习结果
        hasPracticeResults: state => !!state.practiceResults
    }
});

export default store;